<template>
  <div v-if="isChecked(checkKey, groupCheckSelection.selectedKeys)"
       @click="clearCheck" class="el-checkbox is-checked">
    <span class="el-checkbox__input is-checked">
      <span class="el-checkbox__inner"></span>
    </span>
  </div>
  <div class="el-checkbox" v-else @click="select">
    <span class="el-checkbox__input">
      <span class="el-checkbox__inner"></span>
    </span>
  </div>
</template>

<script>
import {isEmpty} from '@/utils/CommonUtils';

export default {
  name: 'FCheckBox',
  inject: ['groupCheckSelection'],
  props: {
    checkKey: {
      type: String,
      default: undefined
    }
  },
  created() {
    this.addBoxKey();
  },
  mounted() {
    this.addBoxKey();
  },
  methods: {
    clearCheck() {
      let index = this.groupCheckSelection.selectedKeys.findIndex(s => s === this.checkKey);
      if (index !== -1) {
        this.groupCheckSelection.selectedKeys.splice(index, 1);
      }
      this.groupCheckSelection.onChange();
    },
    isChecked(checkKey, selectedKeys) {
      if (isEmpty(selectedKeys)) selectedKeys = [];
      return selectedKeys.findIndex(s => s === checkKey) !== -1;
    },
    select() {
      this.groupCheckSelection.selectedKeys.push(this.checkKey);
      this.groupCheckSelection.onChange();
    },
    addBoxKey() {
      if (isEmpty(this.checkKey)) {
        return;
      }
      if (this.groupCheckSelection.checkBoxKeySet.has(this.checkKey)) {
        this.$nextTick(() => {
          this.groupCheckSelection.onChange();
        });
      }
      this.groupCheckSelection.checkBoxKeySet.add(this.checkKey);
    },
    resolveRedundantSelectedKeys() {
      let list = this.groupCheckSelection.selectedKeys.filter(key => {
        return this.groupCheckSelection.checkBoxKeySet.has(key);
      });

      this.groupCheckSelection.selectedKeys.splice(0, this.groupCheckSelection.selectedKeys.length);
      this.groupCheckSelection.selectedKeys.push(...list);
      this.groupCheckSelection.onChange();
    },
  },
  beforeUnmount() {
    this.groupCheckSelection.checkBoxKeySet.delete(this.checkKey);
    this.$nextTick(this.resolveRedundantSelectedKeys);
  },
  updated() {
    this.addBoxKey();
  }
};
</script>
